import { FC, useEffect, useRef } from 'react';
import { init as echartsInit, EChartsOption } from 'echarts';
import useContainer from '@/hooks/use-container';

interface ReactEchartsProps {
  option: EChartsOption;
  width?: number;
  height?: string;
}

const ReactEcharts: FC<ReactEchartsProps> = ({ option, height }) => {
  const chartRef: any = useRef(null);
  const canvasRef: any = useRef(null);

  const { width } = useContainer(chartRef);

  const handleResize = () => canvasRef?.current?.resize();

  const init = () => {
    if (canvasRef?.current) {
      // 建议替换为 ResizeObserver （2023.5.25）
      window.removeEventListener('resize', handleResize);
    }

    canvasRef.current = echartsInit(chartRef?.current as HTMLElement);

    canvasRef.current.setOption(option);
    window.addEventListener('resize', handleResize);
  };

  useEffect(() => {
    handleResize();
  }, [width]);
  useEffect(() => {
    init();

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [option]);

  return <div ref={chartRef} style={{ height: height ?? '600px' }} />;
};

export default ReactEcharts;
